package com.zhaosc.rmi;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import org.springframework.context.ApplicationContext;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhaosc.configbean.Service;

public class SoaRmiImpl extends UnicastRemoteObject implements SoaRmi {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3341952116784127291L;

	protected SoaRmiImpl() throws RemoteException {
		super();
	}

	@Override
	public String invoke(String param) throws RemoteException {
		 JSONObject requetParams=JSONObject.parseObject(param);
		 
		 String serviceId=requetParams.getString("serviceId");
		 String methodName=requetParams.getString("methodName");
		 JSONArray paramTypes=requetParams.getJSONArray("paramTypes");
		 JSONArray methodParams=requetParams.getJSONArray("methodParams");
		 
		 Object[] objs=null;
		 
		 if(methodParams!=null){
			 objs=new Object[methodParams.size()];
			 int i=0;
			 for(Object o:methodParams){
				 objs[i++]=o;
			 }
		 }
		 
		 ApplicationContext application=Service.getApplication();
		 
		 Object serviceBean=application.getBean(serviceId);
		 
		 Method method=getMethod(serviceBean,methodName,paramTypes);
		 if(method!=null){
			 Object result=null;
			 try {
				result=method.invoke(serviceBean, objs);
				if(result!=null){
					return result.toString();
				}
			 } catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		 }else{
			 return "*********no such method**********";
		 }
		 
		 return null;
	}

	private Method getMethod(Object serviceBean, String methodName, JSONArray paramTypes) {
		
		Method[] methods=serviceBean.getClass().getMethods();
		
		outer:for(Method method :methods){
			if(method.getName().equals(methodName.trim())){
				Class<?>[] types= method.getParameterTypes();
			
				//比较参数个数
				if(types.length==paramTypes.size()){
					for (int i = 0; i < types.length; i++) {
						//比较参数类型
						if(!types[i].toString().equals(paramTypes.get(i).toString())){
							continue outer;
						}
					}
					return method;
				}
			}
		}
		
		return null;
	}
	
	

}
